package com.yili.oa.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yili.oa.entity.SearchBase;
import com.yili.oa.entity.TableBase;
import com.yili.oa.models.Permission;
import com.yili.oa.models.Role;
import com.yili.oa.service.PermisService;
import com.yili.oa.service.RoleService;
import com.yili.oa.utils.Exception.AjaxException;
import com.yili.oa.utils.ListUtils;
import com.yili.oa.vo.request.RoleDataReq;
import com.yili.oa.vo.response.RoleDataRes;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * @author lxr
 * @version v0.01
 * @date 2019/3/27 0027
 * @email 200890949@qq.com
 */
@Controller
@RequestMapping("/sys/role")
public class RoleApi {

    @Autowired
    private PermisService permisService;

    @Autowired
    private RoleService roleService;

    /**
     * 跳转到添加页面
     * @return
     */
    @RequestMapping("/addButton")
    public String addButton(ModelMap modelAndView){
        List<Permission> list = permisService.getList(null);
        modelAndView.addAttribute("permission",list);
        return "view/user/roleAdd";
    }
    /**
     * 跳转到添加页面
     * @return
     */
    @RequestMapping("/list")
    @ResponseBody
    public TableBase list(SearchBase search){
        if (search==null){
            search = new SearchBase();
        }
        PageHelper.startPage(search.getPage(),search.getLimit());
        List<Role> list =  roleService.getList(search);
        PageInfo pageInfo = new PageInfo<>(list,search.getLimit());
        List<RoleDataRes> resultList = new ArrayList<>();
        for (Role role:
             list) {
            RoleDataRes rdr = new RoleDataRes();
            BeanUtils.copyProperties(role, rdr);
            StringBuffer sb = new StringBuffer();
            if (StringUtils.isNotBlank(role.getRolePermission())) {
                List<String> permisIds = Arrays.asList(role.getRolePermission().split(","));
                //被删除的权限id
                List<String> beDelPermisIds = new ArrayList<>();
                for (String permisId :
                        permisIds) {
                    //权限被删除了
                    if (permisService.getById(permisId)==null){
                        beDelPermisIds.add(permisId);
                        continue;
                    }
                    String permisName = permisService.getById(permisId).getPermissionName();
                    if (StringUtils.isNotBlank(sb.toString())) {
                        sb.append("," + permisName);
                    } else {
                        sb.append(permisName);
                    }
                }
                //移除被删除的权限
                if (ListUtils.isNotNullOrEmpty(beDelPermisIds)){
                    for (String id:
                         beDelPermisIds) {
                        new ArrayList<String>(permisIds).remove(id);
                    }
                    roleService.updPermission(role.getRoleId(),permisIds);
                }
            }
            if (StringUtils.isNotBlank(sb.toString())) {
                rdr.setRolePermission(sb.toString());
            }
            resultList.add(rdr);
        }
        TableBase tableBase  = new TableBase();
        tableBase.setData(resultList);
        tableBase.setCode(0);
        tableBase.setMsg("");
        tableBase.setCount(pageInfo.getTotal());
        return tableBase;
    }

    /**
     * 添加角色
     * @return
     */
    @PostMapping("/add")
    @ResponseBody
    public String add(RoleDataReq roleDataReq){
        List<String> list = new ArrayList<>();
        if (StringUtils.isNotBlank(roleDataReq.getRolePermission())) {
            String[] strs = roleDataReq.getRolePermission().split(",");
            list = Arrays.asList(strs);
        }
        if (StringUtils.isBlank(roleDataReq.getRoleId())) {
            //查名字是否重复
            Boolean result = roleService.checkName(roleDataReq.getRoleName(),null);
            if (!result){
                throw new AjaxException("该角色已存在");
            }
            //查code是否重复
            Boolean result2 = roleService.checkCode(roleDataReq.getRoleKey(),null);
            if (!result2){
                throw new AjaxException("该code已存在");
            }
            roleService.add(roleDataReq, list);
        }else {
            Boolean result = roleService.checkName(roleDataReq.getRoleName(),roleDataReq.getRoleId());
            if (!result){
                throw new AjaxException("该角色已存在");
            }
            Boolean result2 = roleService.checkCode(roleDataReq.getRoleKey(),roleDataReq.getRoleId());
            if (!result2){
                throw new AjaxException("该code已存在");
            }
            roleService.update(roleDataReq, list);
        }
        return "success";
    }

    /**
     * 跳转到添加页面
     * @return
     */
    @GetMapping("/editButton/{roleId}")
    public String editButton(@PathVariable("roleId") String roleId, ModelMap modelAndView){
        if (StringUtils.isBlank(roleId)){
            throw new AjaxException("该角色不存在");
        }
        modelAndView.put("info", roleService.getById(roleId));
        Role role = roleService.getById(roleId);
        if (role==null){
            throw new AjaxException("该角色不存在");
        }
        if (StringUtils.isNotBlank(role.getRolePermission())){
            modelAndView.put("permisIds", role.getRolePermission());
        }

        List<Permission> list = permisService.getList(null);
        modelAndView.addAttribute("permission",list);
        return "view/user/roleAdd";
    }

    @PostMapping("/delete")
    @ResponseBody
    public Map<String,String> edit(@RequestBody String[] roleIds) {
        Map<String, String> map = new HashMap<>();
        if (roleIds==null){
            throw new AjaxException("请选择要删除的角色");
        }
        List<String> list = Arrays.asList(roleIds);
        roleService.del(list);
        map.put("success", "1");
        return map;
    }
}
